import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

/**
 *  hover 悬停 demo
 * 
 */

export default function(context: vscode.ExtensionContext) {
	const languagesID = 'markdown'; // 语言类型
    context.subscriptions.push(vscode.languages.registerHoverProvider(languagesID, {
		provideHover
	}));

}


function provideHover(document:vscode.TextDocument, position:vscode.Position, 
	token: vscode.CancellationToken): vscode.Hover {

	const fileName	= document.fileName;
	const workDir	 = path.dirname(fileName);
	const word		= document.getText(document.getWordRangeAtPosition(position));

	if (/\/package\.json$/.test(fileName)) {
		console.log('进入provideHover方法');
		const json = document.getText();
		if (new RegExp(`"(dependencies|devDependencies)":\\s*?\\{[\\s\\S]*?
			${word.replace(/\//g, '\\/')}[\\s\\S]*?\\}`, 'gm').test(json)) {
			let destPath = `${workDir}/node_modules/${word.replace(/"/g, '')}/package.json`;
			if (fs.existsSync(destPath)) {
				const content = require(destPath);
				console.log('hover已生效');
				// hover内容支持markdown语法
				return new vscode.Hover(`* **名称**：${content.name}\n* **版本**：${content.version}\n* **许可协议**：${content.license}`);
			}
		}
	} 
	return new vscode.Hover('### 暂无信息');
}